<!--
*  2021-03-15
*  织造 / 落布  流程
-->
<template>
  <div
    id="app"
    class="warping"
    tabindex="-1"
    ref="tabDiv"
    :style="{ top: top }"
  >
    <!-- 头部导航 -->
    <van-nav-bar
      left-arrow
      :title="params.stepName"
      left-text="重新扫码"
      @click-left="onClickLeft"
    >
    </van-nav-bar>
    <!-- 确认信息 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
      :listenScroll="true"
      @scroll="onScroll"
    >
      <van-cell-group class="warping-cell">
        <!-- 确认数据 -->
        <van-cell
          v-for="(data, index) in tableData"
          :key="index"
          :class="data.newValue ? 'active' : 'default'"
          v-show="
            data.field !== 'yarnLonArrangeView' &&
            data.field !== 'yarnLatArrangeView'
          "
        >
          <template #title>
            <span v-html="data.label"></span>
            <span>{{ data.originalValue }}</span>
            <span v-if="data.opt == 1">{{ data.value }}</span>
            <van-checkbox
              v-else
              v-model="data.value"
              shape="square"
              disabled
            ></van-checkbox>
          </template>
          <template v-if="data.opt == 1" #default>
            <van-field
              v-model="data.newValue"
              :type="data.field == 'remark' ? 'text' : 'tel'"
              placeholder="请输入"
              @focus="onFocus(index)"
              @blur="onBlur(index)"
              @input="onChangeInputVal(data)"
            />
          </template>
          <template v-else #default>
            <van-checkbox v-model="data.newValue" shape="square"></van-checkbox>
          </template>
        </van-cell>
        <!-- 经纱排列 -->
        <van-cell
          v-show="stepNo === 6"
          title="经纱排列"
          :class="
            checked ? 'warping-yarn_cell cell-active' : 'warping-yarn_cell'
          "
        >
          <template slot="label">
            <div class="warping-yarn_view">
              <template v-for="(data, index) in yarnLonArrangeViewArr">
                <!-- 无层级 -->
                <div v-if="data.level == 0" :key="index + defaultIndex">
                  <span>{{ data.value }}</span>
                </div>
                <div v-else :key="index + defaultIndex">
                  <!-- 一层 -->
                  <div v-if="data.level == 1" class="level1">
                    <span
                      v-for="(level1, index1) in data.value"
                      :key="index1 + defaultIndex + level1"
                      >{{ level1 }}</span
                    >
                    <i>{{ data.loopNum }}</i>
                  </div>
                  <!-- 二层 -->
                  <div v-if="data.level == 2" class="level2">
                    <div
                      v-for="(count, index2) in data.value"
                      :key="index2 + defaultIndex + count"
                    >
                      <span v-if="typeof count === 'string'">{{ count }}</span>
                      <div v-else class="level1">
                        <span
                          v-for="(value, index3) in count.value"
                          :key="index3 + defaultIndex + value"
                          >{{ value }}</span
                        >
                        <i>{{ count.loopNum }}</i>
                      </div>
                    </div>
                    <i>{{ data.loopNum }}</i>
                  </div>
                  <!-- 三层 -->
                  <div v-if="data.level == 3" class="level3">
                    <div
                      v-for="(count, index4) in data.value"
                      :key="index4 + defaultIndex + count"
                    >
                      <span v-if="typeof count === 'string'">{{ count }}</span>
                      <div v-else class="level2">
                        <div
                          v-for="(count2, index5) in count.value"
                          :key="index5 + defaultIndex + count2"
                        >
                          <span v-if="typeof count2 === 'string'">{{
                            count2
                          }}</span>
                          <div v-else class="level1">
                            <span
                              v-for="(count3, index6) in count2.value"
                              :key="index6 + defaultIndex + count3"
                            >
                              {{ count3 }}</span
                            >
                            <i>{{ count2.loopNum }}</i>
                          </div>
                          <i>{{ count.loopNum }}</i>
                        </div>
                      </div>
                      <i>{{ data.loopNum }}</i>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </template>
          <template #default>
            <van-checkbox v-model="checked" shape="square"></van-checkbox>
          </template>
        </van-cell>
        <!-- 纬纱排列 -->
        <van-cell
          v-show="stepNo === 15"
          title="纬纱排列"
          :class="
            checked ? 'warping-yarn_cell cell-active' : 'warping-yarn_cell'
          "
        >
          <template slot="label">
            <div class="warping-yarn_view">
              <template v-for="(data, index) in yarnLatArrangeViewArr">
                <!-- 无层级 -->
                <div v-if="data.level == 0" :key="index + defaultIndex">
                  <span>{{ data.value }}</span>
                </div>
                <div v-else :key="index + defaultIndex">
                  <!-- 一层 -->
                  <div v-if="data.level == 1" class="level1">
                    <span
                      v-for="(level1, index1) in data.value"
                      :key="index1 + defaultIndex + level1"
                      >{{ level1 }}</span
                    >
                    <i>{{ data.loopNum }}</i>
                  </div>
                  <!-- 二层 -->
                  <div v-if="data.level == 2" class="level2">
                    <div
                      v-for="(count, index2) in data.value"
                      :key="index2 + defaultIndex + count"
                    >
                      <span v-if="typeof count === 'string'">{{ count }}</span>
                      <div v-else class="level1">
                        <span
                          v-for="(value, index3) in count.value"
                          :key="index3 + defaultIndex + value"
                          >{{ value }}</span
                        >
                        <i>{{ count.loopNum }}</i>
                      </div>
                    </div>
                    <i>{{ data.loopNum }}</i>
                  </div>
                  <!-- 三层 -->
                  <div v-if="data.level == 3" class="level3">
                    <div
                      v-for="(count, index4) in data.value"
                      :key="index4 + defaultIndex + count"
                    >
                      <span v-if="typeof count === 'string'">{{ count }}</span>
                      <div v-else class="level2">
                        <div
                          v-for="(count2, index5) in count.value"
                          :key="index5 + defaultIndex + count2"
                        >
                          <span v-if="typeof count2 === 'string'">{{
                            count2
                          }}</span>
                          <div v-else class="level1">
                            <span
                              v-for="(count3, index6) in count2.value"
                              :key="index6 + defaultIndex + count3"
                            >
                              {{ count3 }}</span
                            >
                            <i>{{ count2.loopNum }}</i>
                          </div>
                          <i>{{ count.loopNum }}</i>
                        </div>
                      </div>
                      <i>{{ data.loopNum }}</i>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </template>
          <template #default>
            <van-checkbox v-model="checked" shape="square"></van-checkbox>
          </template>
        </van-cell>
        <!-- 提交按钮 -->
        <van-button
          v-show="tableData.length !== 0"
          class="warping-btn"
          @click="userClickBtn"
          >确认</van-button
        >
      </van-cell-group>
    </better-scroll>

    <van-dialog
      v-model="isLogin"
      className="login-dialog"
      title="确认重新扫码？"
      show-cancel-button
      confirm-button-text="重新扫码"
      @confirm="onClickBack"
    >
      <span>扫码后需重新登陆</span>
    </van-dialog>

    <!-- 警报 -->
    <van-popup
      v-model="warning"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <van-dialog
        v-model="warning"
        className="login-dialog warning-bg"
        title="请确认"
        :show-cancel-button="false"
        confirm-button-text="确认"
        @confirm="warning = false"
      >
        <span>{{ warningText }}</span>
      </van-dialog>
    </van-popup>
  </div>
</template>

<script>
import {
  getConfirmStep,
  getNextCommit,
  getNextInfo,
  getTaskAcceptNext,
  getTaskAccept,
} from "@/api/warping";
import { getTaskStep, getInit } from "@/api/login";
import { openWin, randomStr, getFloat } from "@/utils/index";
import { deepCopy } from "@/utils/index";
import dayjs from "dayjs";
import {loadWeavingCraftDetailByCraftData} from "@/utils/weaving";
export default {
  name: "groupLeader",
  data() {
    return {
      tableData: [
        // { value: 123, opt: 1, originalValue: 222, label: "xxx" },
        // { value: '', opt: 1, originalValue: '', label: "xxx" },
        // { value: 123, opt: 2, originalValue: 222, label: "xxx" },
        // { value: "", opt: 2, originalValue: 222, label: "xxx" },
        // { value: "", opt: 1, originalValue: 222, label: "xxx", field: 'yarnLonArrangeView' },
      ],
      nextStepData: [],
      nextStepAllData: [],
      params: {},
      show: false,
      radioGroup: [],
      radio: "5",
      resId: "",
      tableObj: {},
      demo: "",
      totalPage: 1,
      isLogin: false,
      result: [],
      doingResUrl: "",
      subResIds: [],
      length: "",
      printMac: "",
      metreMac: "",
      pos: {},
      value: "",
      stepNo: 0,
      flowType: "",
      designFormId: '',
      operateWidth: '',
      resArr: [],
      totalLonNum: "",
      planId: "",
      craftNum: "",
      craftSingle: "",
      top: 0,
      scrollH: 0,
      productWidth: "",
      arrange: "",
      leftArrange: "",
      rightArrange: "",
      reedSize: "",
      operateLatDensity: "",
      yarnLatArrangeView: "",
      yarnLonArrangeView: "",
      // "[1:3_1_1A@2B,2:2_2_1@3C,3:5_3_2@5C]+[4:2_1_3B@4C,5:6_2_1A@4]+[6:5_1_3A@5D]",
      yarnLonArrangeViewArr: [],
      yarnLatArrangeViewArr: [],
      latYarnSubtotal: "",
      workerData: [
        {
          opt: 1,
          label: "",
          value: "",
          field: "",
          originalValue: "",
        },
      ],
      code: "",
      lastTime: "",
      nextTime: "",
      lastCode: "",
      nextCode: "",
      loading: false,
      scanStatus: true,
      totalLength: 0,
      defaultIndex: randomStr(),
      finished: false,
      checked: false,
      lastClickTime: 0,
      warning: false,
      warningText: ""
    };
  },
  watch: {
    printMac() {
      if (this.printMac) {
        if (this.params.stepNo === 15) {
          // this.isEnabledBluetooth(false);
        }
      }
    },
    // 监听tableData
    tableData: {
      handler() {
        const that = this;
        this.tableData.forEach((item) => {
          if (item.field === "yarnLatArrangeView") {
            // 纬纱排列
            that.yarnLatArrangeView = item.originalValue;
          } else if (item.field === "yarnLonArrangeView") {
            // 经纱排列
            that.yarnLonArrangeView = item.originalValue;
          }
        });
      },
      deep: true,
    },
    yarnLatArrangeView() {
      this.onGetArrangeView("yarnLatArrange", this.yarnLatArrangeView);
    },
    yarnLonArrangeView() {
      this.onGetArrangeView("yarnLonArrange", this.yarnLonArrangeView);
    },
    // 监听步骤
    stepNo(val) {
      const that = this;
      if (that.flowType === 2 && val === 2) {
        // 获取织造计划  经纱数据
        that.resArr = that.params.resUrl.split(",");
        let url =
          process.env.VUE_APP_YARN_URL +
          that.resArr[0] +
          "/" +
          that.params.resId;
        getConfirmStep(
          {
            resUrl: url,
          },
          (res) => {
            that.designFormId = res.designFormId;
          }
        );
      }
    },
    // 监听设计Id
    designFormId() {
      const that = this;
      let url =
        process.env.VUE_APP_YARN_URL + that.resArr[1] + "/" + that.designFormId;
      getConfirmStep(
        {
          resUrl: url,
        },
        (res) => {
          that.operateWidth = res.operateWidth; // 上机筘幅 / 幅宽
        }
      );
    },
  },
  mounted() {
    const that = this;
    // this.onGetArrangeView("yarnLonArrange", this.yarnLonArrangeView);
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn();
      });
    } else {
      window.apiready = () => {
        that.initFn();
      };
    }
  },
  methods: {
    //初始化
    initFn() {
      const that = this;
      that.params = window.api.pageParam;
      that.stepNo = window.api.pageParam.stepNo;
      that.flowType = window.api.pageParam.flowType;
      // 获取tableData数据
      that.onGetTableData();
      that.onGetInit();
      // 监听页面消失的时候，关掉页面就可以了
      window.api.addEventListener({
        name: "viewdisappear",
      }, function () {
        window.api.closeWin();
      });
    },

    // 重新扫码
    onClickLeft() {
      this.isLogin = true;
    },
    // 重新扫码
    onClickBack() {
      this.tableData = [];
      openWin("index");
    },
    // 打印初始化
    onGetInit() {
      this.printMac = "";
      this.metreMac = "";
      this.pos = {};
      const that = this;
      getInit({}, (res) => {
        let resultArr = eval("(" + res.propertyValue + ")");
        resultArr.forEach((item) => {
          // alert(JSON.stringify(item))
          if (item.type == "1") {
            that.printMac = item.mac;
            let posData = item.pos.split(",");
            that.pos = {
              x: Number(posData[0]),
              y: Number(posData[1]),
            };
          } else if (item.type == "2") {
            that.metreMac = item.mac;
          }
        });
      });
    },
    // 获取table数据
    onGetTableData() {
      const that = this;
      let url =
        process.env.VUE_APP_YARN_URL +
        that.params.nextResUrl +
        "/" +
        that.params.stepId;
      // 织造流程
      if (that.params.stepNo === 15) {
        url =
          process.env.VUE_APP_YARN_URL +
          that.params.nextResUrl +
          "?stepId=" +
          that.params.stepId +
          "&count=3";
      }
      getConfirmStep(
        {
          resUrl: url,
        },
        (res) => {
          // 落布流程
          // console.log(res, "流程");
          if (that.params.flowType === 2 && that.params.stepNo !== 15) {
            res.items.forEach((item) => {
              if (item.field == "remark") {
                item.value = item.value ? item.value : "无";
                item.newValue = item.value ? item.value : "无";
              }
            });
          }
          // 第一步流程
          if (res != null && res.constructor === Object) {
            that.tableData = res.items;
          } else {
            res.forEach((items) => {
              items.items.forEach((item) => {
                that.yarnLatArrangeView =
                  item.field === "yarnLatArrangeView" ? item.originalValue : "";
                item.newValue = "";
                that.tableData.push(item);
              });
            });
          }
        }
      );
    },
    // 获取焦点页面上移
    onFocus(index) {
      this.currIndex = index;
      this.top = index > 2 ? -((index - 2) * 97) - this.scrollH + "px" : 0;
    },
    // 失去焦点 还原
    onBlur(index) {
      if (index === 5) {
        this.top = 0;
      }
    },
    // 输入是否正常
    onChangeInputVal(data) {
      this.warning = false;
      if (data.field === "greyClothWeight") {
        // 克重
        if (data.newValue.length === data.originalValue.toString().length) {
          if (
            data.newValue > Number(data.originalValue) + 21 ||
            data.newValue < Number(data.originalValue) - 21
          ) {
            // 警报
            this.warningText = "米克重超警戒值";
            this.$refs.tabDiv.focus();
            this.warning = true;
          }
        }
      } else if (data.field === "operateWidth" && this.stepNo > 10) {
        // 下机门幅
        let index = data.originalValue.toString().indexOf(".");
        let bool;
        if (index == -1) {
          bool = data.newValue.length === data.originalValue.toString().length;
        } else {
          bool =
            data.originalValue.toString().length - 2 <= data.newValue.length;
        }
        if (bool) {
          if (Number(data.value) < (Number(data.originalValue) - Math.round(data.originalValue * 0.07)) ||
              Number(data.value) > (Number(data.originalValue) + Math.round(data.originalValue * 0.04))) {
            // 警报
            this.warningText = "下机门幅超警戒值";
            this.$refs.tabDiv.focus();
            this.warning = true;
          }
        }
      } else if (data.field === "lonSpindleNum") {
        // 筒只数
        let totalLonNum = "";
        let lonKnotNum = "";
        this.tableData.forEach((item) => {
          if (item.field === "totalLonNum") {
            // 总经
            totalLonNum = item.originalValue;
          } else if (item.field === "lonKnotNum") {
            // 结数
            lonKnotNum = Math.ceil(totalLonNum / data.newValue);
            item.newValue = Math.ceil(totalLonNum / data.newValue);
          } else if (item.field === "lonKnotWidth") {
            // 结阔
            item.newValue = getFloat(
              ((data.newValue / totalLonNum) * 10 * this.operateWidth), 1
            );
          } else if (item.field === "lonNoKnotNum") {
            // 末结
             setTimeout(() => {
               item.newValue = (totalLonNum - (data.newValue*lonKnotNum));
               this.$forceUpdate();
             }, 500)
          }
        });
      }
    },
    // 滚动高度
    onScroll(pos) {
      this.scrollH = pos.y;
    },
    // 经纬视图
    onGetArrangeView(type, data) {
      let responArr = data.split("+");
      let resultArr = [];
      let firstArr = [];
      let secondArr = [];
      responArr.forEach((item) => {
        let param = {};
        // 无层级
        if (item.indexOf("@") === -1) {
          param.level = 0;
          param.value = item;
        } else {
          // 去掉[]  待处理数组
          let ergodicData = item.replace(/\[|\]/g, "").split(",");
          // 若 只有一级
          if (ergodicData.length === 1) {
            let data = ergodicData[0].split(":")[1].split("_");
            param.loopNum = data[0];
            param.level = data[1];
            param.value = data[2].split("@");
          } else {
            // 多级情况
            let lastData = ergodicData.pop(); // 取出最外层
            let lastObj = lastData.split(":")[1].split("_");
            let lastValue = lastObj[2].split("@");
            param.loopNum = lastObj[0];
            param.level = lastObj[1];
            param.value = [];
            // 遍历 最外层数据
            lastValue.forEach((item) => {
              if (this.$getInteger(item)) {
                param.value.push({ id: item });
              } else {
                param.value.push(item);
              }
            });

            ergodicData.forEach((item) => {
              let arr = item.split(":");
              let index = arr[1].indexOf("_");
              let lastIndex = arr[1].lastIndexOf("_");
              if (arr[1].slice(index + 1, lastIndex) == 1) {
                firstArr.push({
                  id: arr[0],
                  loopNum: arr[1].slice(0, index),
                  level: 1,
                  value: arr[1].slice(lastIndex + 1, arr[1].length).split("@"),
                });
              } else {
                let data = {};
                data.id = arr[0];
                data.loopNum = arr[1].slice(0, index);
                data.level = 2;
                data.value = [];
                arr[1]
                  .slice(lastIndex + 1, arr[1].length)
                  .split("@")
                  .forEach((m) => {
                    if (this.$getInteger(m)) {
                      data.value.push({ id: m });
                    } else {
                      data.value.push(m);
                    }
                  });
                secondArr.push(data);
              }
            });
          }
        }
        resultArr.push(param);
      });
      // 组装数组
      this.onGetFilterArr(firstArr, secondArr);
      this.onGetFilterArr(secondArr, resultArr);
      if (type === "yarnLonArrange") {
        this.yarnLonArrangeViewArr = resultArr;
      } else {
        this.yarnLatArrangeViewArr = resultArr;
        // console.log(resultArr);
      }
    },
    onGetFilterArr(arr1, arr2) {
      for (let k in arr1) {
        let flag = false;
        for (let i in arr2) {
          if (arr2[i].value) {
            for (let j in arr2[i].value) {
              if (typeof arr2[i].value[j] === "object") {
                if (arr1[k].id === arr2[i].value[j].id) {
                  flag = true;
                  arr2[i].value[j] = arr1[k];
                  break;
                }
              }
            }
          }
        }
        if (!flag) {
          arr2.push(arr1[k]);
        }
      }
    },
    // 节流 3s 操作一次
    userClickBtn() {
      let that = this;
      // 设置定时器
      let timer;
      // 设置现在的时间
      let now = dayjs().valueOf();
      // 当现在的时间减去上次点击的时间小于5s时,给出提示，并结束执行函数
      if (that.lastClickTime && now - that.lastClickTime < 5000) {
        clearTimeout(timer);
        // this.$toast({
        //   message: "操作频率太快，请勿重复操作！",
        //   type: "fail",
        // });
        // return;
      } else {
        // 若大于3s，则把现在的时间赋值个lastTime
        that.lastClickTime = now;
      }
      timer = setTimeout(function () {
        that.onGetNextInfo();
        // 每次点击按钮都要把最新的时间赋值给lastTime
        that.lastClickTime = dayjs().valueOf();
      }, 200);
    },
    // 获取下一步信息
    onGetNextInfo() {
      const that = this;
      that.nextStepData = [];
      that.nextStepAllData = [];
      // // 获取下一步信息
      getNextInfo(
        {
          flowType: that.params.flowType,
          stepNo: that.params.stepNo,
        },
        function (res) {
          // console.log(res, "提交前一步");
          that.nextStepAllData = res;
          if (that.params.stepNo === 2) {
            // 整经确认
            let data = that.params.nextStepNo.split(",")[0];
            that.nextStepData.push(
              data.split("_")[0] + "@0:" + res[0].depId + "_" + res[0].postId
            );
            that.onGetNextCommit();
          } else {
            that.params.nextStepNo.split(",").forEach((item, i) => {
              that.nextStepData.push(
                item.split("_")[0] + "@0:" + res[i].depId + "_" + res[i].postId
              );
            });
            that.onGetNextCommit();
          }
        }
      );
    },
    // 提交
    onGetNextCommit() {
      const that = this;
      if (that.params.stepNo === 6 || that.params.stepNo === 15) {
        if (!that.checked) {
          that.$toast.fail("必选项不能为空");
          return false;
        } else {
          that.tableData.forEach((item) => {
            if (item.field === "yarnLonArrangeView") {
              item.value = true;
            } else if (item.field === "yarnLatArrangeView") {
              item.value = true;
            }
          });
        }
      }
      // console.log(that.tableData)
      // let result = that.tableData.every((item) => item.value != "");
      // if (!result) {
      //   that.$toast.fail("必选项不能为空");
      //   return false;
      // }
      let newArr = deepCopy(that.tableData);
      newArr.forEach((item) => {
        if (item.value != item.newValue) {
          item.value = item.newValue;
        }
        delete item.newValue;
      });
      let resParams = {
        stepId: that.params.stepId,
        stepNo: that.params.stepNo,
        stepName: that.params.stepName,
        items: newArr,
      };
      getNextCommit(
        {
          taskId: that.params.taskId,
          stepNo: that.params.stepNo,
          nextStepIndex: that.nextStepData.join(","),
          loopCount: "1",
          resId: that.params.resId,
          resParams: JSON.stringify(resParams),
        },
        function (res) {
          that.$toast({
            type: "success",
            message: "确认成功，下一步" + that.params.nextStepName,
            onClose: () => {
              // console.log(res, "成功");
              if (that.params.stepNo === 15) {
                // 当前步骤已完成  查询蓝牙连接状态
                that.onGetTaskAcceptNext();
              } else {
                window.api.closeToWin({ name: "warping" });
                // 跳转首页
                openWin("index");
              }
            },
          });
        }
      );
    },
    // 获取落布流程
    onGetTaskAcceptNext() {
      const that = this;
      getTaskStep(
        {
          resUrl: that.params.qrCode,
        },
        (repon) => {
          // console.log("扫码接口");
          that.doingResUrl = repon[0].doingResUrl;
          // 报工
          that.params = {
            stepId: repon[0].id,
            flowType: repon[0].flowType,
            resId: repon[0].resId,
            stepNo: repon[0].stepNo,
            taskId: repon[0].taskId,
            resUrl: repon[0].resUrl,
            nextResUrl: repon[0].doingResUrl,
            nextStepNo: repon[0].nextStepNo,
            todoResUrl: repon[0].todoResUrl,
            doingResUrl: repon[0].doingResUrl,
            stepName: repon[0].stepName,
            nextStepName: repon[0].nextStepName,
          };
          getTaskAcceptNext({
            resUrl: process.env.VUE_APP_YARN_URL + that.params.todoResUrl + "/" + that.params.resId
          }, res => {
            that.subResIds.splice(0, that.subResIds.length);
            if(res.newFlag) {
              loadWeavingCraftDetailByCraftData({
                craftId: res.id
              }, data => {
                const craftDetails = data.filter(craftDetail => !craftDetail.lonOnly);
                if(craftDetails.length == 0) {
                  that.$toast.fail("盘头下没有确认纬纱的盘头详情");
                  return;
                }
                const totalNum = craftDetails.map(craftDetail => Number(craftDetail.remainNum)).reduce((a, b) => Number(a) + Number(b));
                for(let i=0; i<totalNum; i++) {
                  that.subResIds.push("0");
                }
                that.onGetTaskAccept();
              });
            } else {
              if (res.craftNum) {
                for (let i = 0; i < res.craftNum; i++) {
                  that.subResIds.push("0");
                }
              }
              that.onGetTaskAccept();
            }
          });
        }
      );
    },
    // 接单
    onGetTaskAccept() {
      const that = this;
      let obj = {
        stepNo: 16,
        taskId: that.params.taskId,
        subResIds: that.subResIds,
        stepId: that.params.stepId,
      };
      // 打印
      getTaskAccept(obj, () => {
        that.$toast({
          type: "success",
          message: "落布流程发起成功",
          duration: 1000,
          onClose: () => {
            // that.isEnabledBluetooth(true);
            // 接单成功
            window.api.closeToWin({ name: "warping" });
            // 跳转首页
            openWin("index");
          },
        });
      });
    },

    // 查询蓝牙状态
    isEnabledBluetooth(printStatus) {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.onGetConnectState(printStatus);
            } else {
              that.openBluetooth(printStatus);
            }
          } else {
            that.$message.error("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth(printStatus) {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress(printStatus);
            }
          } else {
            that.listenBluetoothStatus(printStatus);
          }
        });
    },
    listenBluetoothStatus(printStatus) {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.connectBleByMacAddress(printStatus);
            }
          } else {
            that.$message.error("code: " + err.code + " msg: " + err.msg);
          }
        });
    },

    // 查询打印机连接状态
    onGetConnectState(printStatus) {
      const that = this;
      that.$toast({
        type: "loading",
        message: "查询打印机连接状态",
      });
      let obj = window.api.require("xGprinterPlus");
      let ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接  获取打印数据打印
          that.onPrintList();
        } else {
          // 未连接
          that.$toast({
            type: "error",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress(printStatus);
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "error",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress(printStatus);
          },
        });
      }
    },
    // mac 地址连接
    connectBleByMacAddress(printStatus) {
      const that = this;
      that.$toast({
        type: "loading",
        message: "正在连接，请等待",
        duration: 20000,
      });
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress:
            process.env.NODE_ENV === "production"
              ? that.printMac
              : "DC:1D:30:C6:58:8E",
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.$toast.clear();
              // 打印
              if (printStatus) {
                that.onPrintList();
              }
            } else if (ret.message === "连接失败") {
              that.$toast.clear();
              that.$toast.fail("初始化失败");
            }
          } else {
            that.$toast.clear();
            that.$toast.fail(err.msg);
          }
        }
      );
    },
    // 打印列表
    onPrintList() {
      const that = this;
      getTaskAcceptNext(
        {
          resUrl:
            process.env.VUE_APP_YARN_URL +
            that.params.doingResUrl +
            "/" +
            that.params.resId,
        },
        (res) => {
          // console.log(res, "打印");
          res.unshift({});
          that.printData(res);
        }
      );
    },
    printData(res) {
      const that = this;
      that.$toast.loading({
        message: "正在打印",
        forbidClick: true,
        duration: 20000,
        loadingType: "spinner",
      });
      let printCount = res.length;
      let currLength = 0;
      let printData = [];
      res.forEach((item, i) => {
        let url =
          item.qrCode +
          "?taskId=" +
          item.taskId +
          "&craftId=" +
          item.craftId +
          "&craftNo=" +
          item.craftNo;
        // console.log(url, "打印");
        let obj = window.api.require("xGprinterPlus");
        let rows = [
          {
            lineType: "size",
            width: 35,
            height: 25,
          },
          {
            lineType: "gap",
            data: 2,
          },
          {
            lineType: "direction", //设置打印方向
            direction: "forward", //backward|forward
            mirror: "normal", //normal|mirror
          },
          {
            lineType: "cls", // 清除打印缓冲区
          },
          {
            lineType: "text", //绘制简体中文
            x: 80,
            y: 30,
            rotation: 90, // 0|90|180|270
            xscal: 1, //1~10
            yscal: 3, //1~10
            data: "",
          },
        ];
        if (i > 0) {
          rows = [
            {
              lineType: "size",
              width: 35,
              height: 25,
            },
            {
              lineType: "gap",
              data: 2,
            },
            {
              lineType: "direction", //设置打印方向
              direction: "forward", //backward|forward
              mirror: "normal", //normal|mirror
            },
            {
              lineType: "cls", // 清除打印缓冲区
            },
            {
              lineType: "text", //绘制简体中文
              x: 80,
              y: 30,
              rotation: 90, // 0|90|180|270
              xscal: 1, //1~10
              yscal: 1, //1~10
              data: item.designNo,
            },
            {
              lineType: "text", //绘制简体中文
              x: 40,
              y: 30,
              rotation: 90, // 0|90|180|270
              xscal: 1, //1~10
              yscal: 1, //1~10
              data: item.craftNo,
            },
            {
              lineType: "qrcode", // 绘制qrcode
              x: 100,
              y: 20,
              level: "L", //L|M|H|Q
              cellwith: 4,
              rotation: 0, // 0|90|180|270
              data: url,
            },
          ];
        }
        obj.printLabel(
          {
            rows: rows,
          },
          function (ret, err) {
            that.$toast.clear();
            if (ret.status) {
              ++currLength;
              if (currLength === printCount) {
                that.$toast.success("打印完成");
                openWin("index");
              }
            } else {
              printData.push(item);
              that.$toast.fail("打印异常" + err.msg);
            }
          }
        );
      });
    },
  },
};
</script>

<style lang="scss">
.warping {
  position: relative;
  top: 0;
  .public-scroll {
    .warping-cell {
      display: flex;
      flex-direction: column;
      align-items: center;
      .van-cell {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        // height: 70px;
        font-size: 26px;
        &.default {
          .van-cell__title {
            flex: 0 0 80% !important;
            height: 48px;
            display: flex;
            align-items: center;
            span {
              display: inline-block;
              height: 48px;
              line-height: 48px;
              padding: 0 10px;
              flex: 1;
              &:first-child {
                flex: 0 0 80%;
              }
            }
            & > div {
              flex: 1;
            }
          }
          .van-cell__value {
            display: flex;
            justify-content: flex-end;
            .van-field {
              height: 50px;
              padding: 0;
            }
          }
        }

        &.active {
          .van-cell__title {
            flex: 0 0 80% !important;
            height: 48px;
            display: flex;
            align-items: center;
            .van-checkbox--disabled {
              background-color: greenyellow;
              .van-checkbox__icon--disabled {
                .van-icon {
                  background-color: greenyellow;
                  border-color: greenyellow;
                }
              }
            }
            span {
              display: inline-block;
              height: 48px;
              line-height: 48px;
              padding: 0 10px;
              flex: 1;
              background: greenyellow;
              &:first-child {
                flex: 0 0 80%;
              }
            }
            & > div {
              flex: 1;
            }
          }
          .van-cell__value {
            display: flex;
            justify-content: flex-end;
            .van-field {
              height: 50px;
              padding: 0;
            }
          }
        }
        &.warping-yarn_cell {
          &.cell-active {
            .van-cell__title {
              background: greenyellow;
            }
          }
          .van-cell__title {
            flex: 0 0 80%;
            padding: 16px;
          }
          .van-cell__value {
            display: flex;
            justify-content: flex-end;
          }
        }
        &.warping-worker {
          & > .van-cell__value {
            margin-right: 20px;
            .van-icon {
              display: flex;
              align-items: center;
            }
            .van-cell {
              padding-top: 0 !important;
            }
          }
        }
        &:first-child {
          .van-cell__title {
            flex: 1;
          }
        }
        .van-cell__value {
          height: 100%;
          .van-field__body {
            height: 100%;
            .van-field__control {
              height: 100%;
            }
          }
        }
        .van-field {
          padding-right: 0 !important;
        }
      }
      .warping-btn {
        width: 700px;
        height: 100px;
        background: #1677ff;
        border-radius: 2px;
        font-size: 32px;
        color: #ffffff;
        margin-top: 50px;
        // margin-bottom: 100px;
      }

      .van-field__control {
        text-align: right !important;
        font-size: 26px;
      }
    }
  }
  .van-checkbox,
  .van-checkbox__icon,
  .van-icon {
    width: 50px;
    height: 50px;
  }
  .van-icon-success::before {
    position: relative;
    top: 15px;
    font-size: 36px;
  }

  .van-radio {
    height: 50px;
    display: flex;
    align-items: flex-start;
  }

  /* 经纬视图 */
  .warping-yarn_view {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
  }
  .warping-yarn_view > div {
    margin-right: 6px;
    margin-bottom: 20px;
    height: auto !important;
    span {
      margin-right: 0 !important;
      color: #000 !important;
    }
  }

  .level1 {
    position: relative;
    height: 20px;
    border-bottom: 1px solid #000;
    margin-right: 6px;
  }
  .level2 {
    display: flex;
    height: 40px;
    border-bottom: 1px dotted #000;
    position: relative;
    & > div {
      margin-right: 6px;
    }
    margin-right: 6px;
  }
  .level3 {
    display: flex;
    height: 60px;
    border-bottom: 1px solid #000;
    position: relative;
    & > div {
      margin-right: 6px;
    }
    margin-right: 6px;
  }
  .warping-yarn_view div i {
    position: absolute;
    bottom: -18px;
    left: 50%;
    margin-left: -12px;
    font-size: 14px;
  }
}
</style>
